require( '$d/css/common.less' );
require( './style.less' );
require( '$d/js/modules/platformPublic/style.less' );
define( [
  'require',
  'jquery',
  'header',
  'nav',
  'bootstrap',
  'selector',
  'message',
  'bigwe_utils',
  'unauthor',
  'constants',
  'api',
], function( require, $ ) {
  var message = require( 'message' ),
    util = require( 'bigwe_utils' ),
    bwAuthor = require( 'unauthor' ),
    constants = require( 'constants' ),
    InterFace = require( 'api' );
  var param = {
    url: InterFace.MYMESSAGE.MESSAGE,
    data: {
      done: 'list',
      page: 1,
    },
    callBack: message_list,
    p: true,
  };

  var myAjax = function( opt ) {
    message.show( "正在加载" );
    $.ajax( {
      type: 'post',
      url: opt[ 'url' ],
      data: opt[ 'data' ],
      success: function( data ) {
        if ( $.isFunction( opt[ 'callBack' ] ) ) {
          opt[ 'callBack' ]( data );
        }
      },
      error: function( XMLHttpRequest, textStatus, errorThrown ) {
        console.log( textStatus );
        console.log( XMLHttpRequest.status );
        console.log( XMLHttpRequest.readyState );
      },
      complete: function() {
        message.hide();
      }
    } );
  }
  $( '.selectpicker' ).selectpicker();

  function message_list( data ) {
    var data = typeof data === 'string' ? $.parseJSON( data ) : data;
    var html = '',
      page;

    if ( data.ret == '20004' ) {
      message.show( data.msg, 2000 );
      return;
    }
    if ( data.data == '' ) {
      html = '<div class="no_content"><span class="glyphicon glyphicon-flash"></span>暂无消息</div>';
    } else {
      var arts = data.data.data;
      for ( var i in arts ) {
        var art = arts[ i ];
        html += '<div class="main-message"><div class="row"><div class="col-xs-1"><div class="avatar-information"><img src="' + art.headimg + '" alt="" onerror="this.src=\'' + constants.resPath + '/images/default_face.png\';"></div></div><div class="col-xs-5"><p class="message-name">';
        if ( art.alias ) {
          html += art.alias + '<span class="spay_gray">(' + art.nickname + ')</span>';
        } else {
          html += art.nickname;
        }
        var text = art.content;

        var identification = ( !art.messageType || '' || null ) ? '文字' : ( type_identifier[ art.messageType ] );
        html += '<span class="pull-right type_identifier">[' + identification + ']</span></p><div class="message-content">';


        if ( art.messageType == 'text' || art.messageType == null || art.messageType == '' ) {
          if ( cutStr( text, 262 ) ) {
            html += cutStr( text, 262 ) + '&nbsp;...<button class="see_more pull-right">展开</button></div><div class="message_hide">' + text + '<button class="see_more pull-right">收起</button>';
          } else {
            html += text;
          }
        } else if ( art.messageType == 'image' ) {
          html += '<img src="' + text + '"/>';
        } else if ( art.messageType == 'voice' ) {
          html += '<audio controls id="vid' + i + '" class="vid"><source src="' + text + '" >您的浏览器不支持 audio 元素。</audio>' +
            '<div class="voice_play"><span class="iconfont icon-play"></span><p id="vid_t' + i + '"></p></div>';
        } else if ( art.messageType == 'video' || art.messageType == 'shortvideo' ) {
          html += '<video width="200" height="150" preload controls id="_video"><source src="' + text + '" ></video>';
        } else if ( art.messageType == 'link' ) {
          html += '<a href="' + text + '" class="link_address" target="_blank">' + text + '</a>';
        } else if ( art.messageType == 'location' ) {
          html += '<iframe id="geoPage" width=300 height=200 frameborder=0 scrolling="no"src="http://apis.map.qq.com/tools/poimarker?type=0&marker=coord:' + json_reform( text ).location_X + ',' + json_reform( text ).Location_Y + ';addr:' + json_reform( text ).Label + '&zoom=' + json_reform( text ).Scale + '&tonav=0&key=5JBBZ-KVCR5-BDRIS-QJZAJ-YNW2Z-O3BPQ&referer=myapp"></iframe> ';
        }

        html += '</div><input type="hidden" value="' + art.fromUsername + '" class="fromUsername">' +
          '<input type="hidden" value="' + art.ToUsername + '" class="ToUsername">' +
          '<input type="hidden" value="' + art.message_id + '" class="message_id">' +
          '</div><div class="col-xs-6">' +
          '<p class="message-state">' +
          '<span class="message-time">' + art.time + '</span>' +
          '<span class="account-icon glyphicon glyphicon-user"></span>' +
          '<span class="account-name">' + art.user_name + '</span>';
        if ( art.responseText == null || '' ) {
          html += '<span class="message-happens"></span>';
        } else {
          html += '<span class="message-happens">已回复</span>';
        }
        if ( art.sub == 1 ) {
          html += '<span class="message-reply bigwe_default_btn_fff">回复</span>';

        }
        html += '</p></div></div>';
        if ( art.sub == 1 ) {
          html += '<form action=""><div class="reply-edit">' +
            '<textarea name="reply-text" id="reply-text' + art.message_id + '" class="reply-text" placeholder="在此处输入你想回复的内容" onfocus="if (placeholder ==\'在此处输入你想回复的内容\'){placeholder =\'\'}" onblur="if (placeholder ==\'\'){placeholder=\'在此处输入你想回复的内容\'}"></textarea>' +
            '<input type="button" value="提交" class="btn-success bigwe_default_btn sub" info="' + art.verify_info + '" login="' + art.login_account + '" app_id="' + art.app_id + '"/>' +
            '</div></form>';
        }
        html += '</div>';
      }
      page = data.data.totalPage;
    }
    if ( param.p ) {
      if ( data.data == '' ) {
        cont.find( '.message_paging' ).addClass( 'hide' );
      } else {
        cont.find( '.message_paging' ).removeClass( 'hide' );
        paging( page );
      }
      param.p = false;
    }
    $( ".message_show" ).empty().append( html );
    getTime();
  }

  function paging( page ) {
    cont.find( '.message_paging' ).bwPagination( {
      total: page * 10,
      autoVisibility: !0,
      callback: function( index ) {
        param.data.page = index;
        myAjax( param );
      }
    } );
  }

  /*
   * param str 要截取的字符串
   * param L 要截取的字节长度，注意是字节不是字符，一个汉字两个字节
   * return 截取后的字符串
   */
  function cutStr( str, L ) {
    var result = '',
      strlen = str.length, // 字符串长度
      chrlen = str.replace( /[^\x00-\xff]/g, '**' ).length; // 字节长度

    if ( chrlen <= L ) {
      return false;
    }

    for ( var i = 0, j = 0; i < strlen; i++ ) {
      var chr = str.charAt( i );
      if ( /[\x00-\xff]/.test( chr ) ) {
        j++; // ascii码为0-255，一个字符就是一个字节的长度
      } else {
        j += 2; // ascii码为0-255以外，一个字符就是两个字节的长度
      }
      if ( j <= L ) { // 当加上当前字符以后，如果总字节长度小于等于L，则将当前字符真实的+在result后
        result += chr;
      } else { // 反之则说明result已经是不拆分字符的情况下最接近L的值了，直接返回
        return result;
      }
    }
  }

  var cont = $( '.main_content' ),
    orig_id = [];
  if ( !$( '.platf_pblc_choose > div' ).hasClass( 'account_null' ) ) {
    cont.removeClass( 'hide' );
    $( '.account_info>.original_id' ).each( function() {
      orig_id.push( $( this ).val() );
    } );
    param.data.original_id = orig_id;
    myAjax( param );
  } else {
    return;
  }

  function getTime() {
    $( ".message_show audio" ).each( function( k, i ) {
      setTimeout( function() {
        var duration = $( '#' + i.id )[ 0 ].duration;
        if ( isNaN( duration ) ) {
          $( "#vid_t" + ( i.id ).replace( /[^0-9]/ig, "" ) ).html( '0s' );
        } else {
          $( "#vid_t" + ( i.id ).replace( /[^0-9]/ig, "" ) ).html( Math.floor( duration ) + 's' );
        }
      }, 1000 );
    } )
  }

  function json_reform( jn ) {
    var json = {};
    var str = jn.split( ';' );
    for ( i in str ) {
      var l = str[ i ].split( ':' );
      json[ l[ 0 ] ] = l[ 1 ];
    }
    return json;
  }

  var type_identifier = {
    text: '文字',
    image: '图片',
    voice: '语音',
    video: '视频',
    shortvideo: '小视频',
    location: '地理位置',
    link: '链接',
  }

  /*公众号选择*/
  var pl = $( '#public_list' );

  pl.on( 'click', '.account_detail .detail_sub', function() {
    $( this ).addClass( "cover" ).siblings().removeClass( "cover" );
  } ).on( 'click', '.modal-footer .ok', function() {
    pl.modal( 'hide' );
    var _parent = $( '.account_info' );
    var _choice = $( '.cover' );

    var original_id = new Array();

    if ( _choice.index() == 0 ) {
      _choice.siblings().each( function() {
        original_id.push( $( this ).find( '.original_id' ).val() );
      } );
      var or_id = '';
      for ( var i = 0; i < original_id.length; i++ ) {
        or_id += '<input type="hidden" value="' + original_id[ i ] + '" class="original_id">'
      }
      _parent.empty().append( '<p class="all_num">全部公众号</p>' + or_id );
    } else {
      original_id = _choice.find( '.original_id' ).val()
      var variable = "";
      variable = '<input type="hidden" value="' + _choice.find( '.original_id' ).val() + '" class="original_id"><img src="' + _choice.find( ".pub_img" ).prop( "src" ) + '"><div class="public_account"><p class="public_account_name">' + _choice.find( ".pub_name" ).text() + '</p> <p class="public_account_type"><span class="iconfont icon-dingyuehao"></span> <span class="mail-type-name">&nbsp;订阅号</span> </p> </div>';
      _parent.empty().append( variable );
    }
    param.p = true;
    param.data.original_id = original_id;
    param.data.page = '1';
    myAjax( param );
  } );

  /*按照时间筛选*/
  $( '#select_time' ).change( function() {
    var _time = $( this ).val();
    param.p = true;
    param.data.page = 1;
    param.data.select_time = _time;
    myAjax( param );
  } );

  /*按照类型筛选*/
  $( '#type_sel' ).change( function() {
    var type = $( this ).val();
    param.p = true;
    param.data.page = 1;
    param.data.message_type = type;
    myAjax( param );
  } );

  /*搜索*/
  $( '.search_btn' ).click( function() {
    var _search = $( '.search_input' ).val();
    param.p = true;
    param.data.page = 1;
    param.data.search_input = _search;
    myAjax( param );
  } );

  /*展开全文*/
  $( ".message_show" ).on( "click", ".see_more", function() {
    if ( $( this ).text() == '展开' ) {
      $( this ).parent().siblings( '.message_hide' ).show();
      $( this ).parent().hide();
    } else {
      $( this ).parent().siblings( '.message-content' ).show();
      $( this ).parent().hide();
    }
  } );

  /*回复*/
  $( '.message_show' ).on( "click", ".message-reply", function() {
    if ( $( this ).text() == "回复" ) {
      $( '.reply-edit' ).hide();
      $( '.message-reply' ).text( "回复" );
      $( this ).parents( ".main-message" ).find( $( ".reply-edit" ) ).slideDown( "slow" );
      $( this ).text( "收起" );
    } else {
      $( this ).text( "回复" );
      $( this ).parents( ".main-message" ).find( $( ".reply-edit" ) ).slideUp( "slow" );
    }
  } );

  /*图片预览*/
  $( document ).on( 'click', '.message-content > img', function() {
    if ( $( this ).hasClass( 'message_map' ) ) {
      return;
    }
    var src = $( this ).attr( 'src' );
    $( ".img_prev > img" ).attr( 'src', src );
    $( '#img_prev' ).modal( 'toggle' );
  } );

  /*页码跳转*/
  $( ".message_paging" ).on( 'click', '.page_byn', function() {
    isOk = true;
    var search_page = $( '.page_text' ).val();
    var current_page = $( '.current' ).text();
    if ( !search_page || '' || search_page > _page || search_page < 0 ) {
      message.showWarning( "您要跳转的页码不存在", 1000 );
      return;
    }
    if ( search_page == current_page ) {
      message.showWarning( "您输入的是当前页码", 1000 );
      return;
    }
    $( window ).scrollTop( 0 );
    param.data.page = search_page;
    myAjax( param );
    $( '.page_text' ).val( '' );
  } );
  $( ".paging" ).on( 'keydown', '.page_text', function() {
    if ( event.keyCode == "13" ) {
      $( '.page_byn' ).click();
    }
  } );

  /*播放语音*/
  $( ".message_show" ).on( 'click', '.voice_play > span', function() {
    var _this = $( this );
    var id = _this.parent().siblings( 'audio' ).attr( 'id' );
    var vid = $( "#" + id );
    var vidDOM = vid[ 0 ];

    if ( vidDOM.paused ) {
      vidDOM.play();
      _this.addClass( 'icon-voice ' ).removeClass( 'icon-play' );
      vidDOM.onended = function() {
        _this.removeClass( 'icon-voice ' ).addClass( 'icon-play' );
      }
    } else {
      vidDOM.pause();
      _this.removeClass( 'icon-voice ' ).addClass( 'icon-play' );
    };
    return false;
  } );

  /*提交回复*/
  var login_account, app_id;
  $( '.message_show' ).on( "click", ".sub", function() {
    $( this ).siblings( '.reply-text' ).addClass( 'send_out' );
    var info = $( this ).attr( 'info' );
    login_account = $( this ).attr( 'login' );
    app_id = $( this ).attr( 'app_id' );
    if ( $( '.send_out' ).val() == '' ) {
      message.showWarning( "请输入回复信息！", message.showTime );
      $( '.send_out' ).focus();
      return;
    }
    if ( info == -1 ) {
      sign_in();
    } else {
      reply();
    }
  } );

  function sign_in() {
    var author_data = {
      login_account: login_account,
      appid: app_id
    }
    if ( !login_account ) {
      author_data.isNewAuthor = !0
    }
    bwAuthor.doAuthorOperate( author_data, function( data ) {
      if ( !login_account && data.login_account ) {
        login_account = data.login_account;
      }
      reply();
    } );
  }

  function reply() {
    var ta = $( ".send_out" );
    var parent = ta.parent();
    var responseText = ta.val();
    var tr = '已回复';
    var sp = parent.parent().parent();
    var te = parent.find( ".reply-text" );
    var fromUsername = parent.parent().parent().find( '.fromUsername' ).val();
    var ToUsername = parent.parent().parent().find( '.ToUsername' ).val();
    var message_id = parent.parent().parent().find( '.message_id' ).val();
    $.post( 'my_message/message', {
      responseText: responseText,
      ToUsername: ToUsername,
      fromUsername: fromUsername,
      message_id: message_id,
      done: 'sub'
    }, function( data ) {
      var data = eval( '(' + data + ')' );
      if ( data.ret == 0 ) {
        te.val( '' );
        sp.find( '.message-happens' ).html( tr );
        parent.removeAttr( 'style' );
        $( ".message-reply" ).text( '回复' );
        message.show( "发送成功", message.showTime );
      } else if ( data[ 'ret' ] == 20100 ) {
        message.showWarning( '发送失败,' + data[ 'msg' ], message.showTime );
      }
    } )
    $( '.send_out' ).removeClass( 'send_out' );
  }
} )
